package com.dwjm.exam.stu_list;

import com.google.gson.Gson;

import com.dwjm.utils.CommonResult;
import com.dwjm.exam.pojo.PageResult;
import com.dwjm.exam.pojo.Student;
import com.dwjm.exam.stu_list.StudentDao;
import com.dwjm.exam.stu_list.StudentDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 学生列表处理器
 */
@WebServlet("/student/list")
public class StudentListHandler extends HttpServlet {
    private StudentDao studentDao = new StudentDaoImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        int page = 1;
        int size = 10;

        try {
            String pageParam = req.getParameter("page");
            String sizeParam = req.getParameter("size");

            if (pageParam != null) {
                page = Integer.parseInt(pageParam);
            }
            if (sizeParam != null) {
                size = Integer.parseInt(sizeParam);
            }

            if ("search".equals(action)) {
                String name = req.getParameter("name");
                String dormId = req.getParameter("dormId");
                PageResult<Student> result = studentDao.searchStudents(page, size, name, dormId);
                sendResponse(resp, CommonResult.success(result));
            } else {
                PageResult<Student> result = studentDao.getStudentsByPage(page, size);
                sendResponse(resp, CommonResult.success(result));
            }
        } catch (NumberFormatException e) {
            sendResponse(resp, CommonResult.fail(400, "参数错误: page和size必须是整数"));
        } catch (Exception e) {
            sendResponse(resp, CommonResult.fail(500, "服务器内部错误"));
        }
    }

    private void sendResponse(HttpServletResponse resp, CommonResult<?> result) throws IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        Gson gson = new Gson();
        String json = gson.toJson(result);
        resp.getWriter().write(json);
    }
}